package com.zzyl.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AlertJob {

    @Autowired
    private AlertRuleMapper alertRuleMapper;
    
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private AlertRuleService alertRuleService;

    @Scheduled(cron = "0/30 * * * * ?")
    public void deviceDataAlertFilter(){

        //查询所有规则
        List<AlertRule> alertRules = alertRuleMapper.selectByFunctionId(null, null, null);
        if(CollUtil.isEmpty(alertRules)){
            return;
        }
        
        //查询所有的上报的数据
        List<Object> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA_KEY);
        if(CollUtil.isEmpty(values)){
            return;
        }

        //解析数据到list<DeviceDataVo>
        List<DeviceDataVo> dataVoList = new ArrayList<>();
        values.forEach(v-> dataVoList.addAll(JSONUtil.toList(v.toString(),DeviceDataVo.class)));

        //获取每一条数据，匹配规则
        dataVoList.forEach(d->alertRuleService.alertFilter(d));

    }
}
